//
//  SSOrderDetailController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/3/5.
//

import UIKit

import SwiftyJSON

class SSOrderDetailController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var contactInfos = [SSCellModel]()
    var orderInfos = [SSCellModel]()
    var incomeInfos = [SSCellModel]()
    var salaryInfos = [SSCellModel]()
    var sectionTitles:Array<String> = []
    var orderDetail = SSOrder()
    var orderNo = ""
    var totalArr:Array<Array<ListCombo>> = []
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUIs()
        network()
        
        print("pingmu:\(ScreenWidth)\(ScreenHeight)")
    }
    
    //组装数据
    func handleData() {
//        self.sectionTitles = ["套餐信息","套餐信息","预定信息","订单信息"]
        self.sectionTitles.append("订单金额")
        self.sectionTitles.append("订单收入")
        self.sectionTitles.append("预定信息")
        self.sectionTitles.append("订单信息")
        
        let salaryTitles = [
             "订单总价",
             "优惠金额",
             "合计",
             "待付款"
         ]
        
        let salaryDetails = [
            "$\(orderDetail.originalTotal)",
            "$\(orderDetail.couponMoney)",
            "$\(orderDetail.total)",
            "$\(orderDetail.pendingMoney)"
          ]
        
        for(index, title) in salaryTitles.enumerated(){
            let m = SSCellModel()
            m.title = title
            m.detail = salaryDetails[index]
            m.cellHeight = 44
            m.textColor = "#666666"
            self.salaryInfos.append(m)
        }
        
        let incomeTitles = [
             "基础收入",
             "奖励收入",
             "距离补贴",
             "订单总收入"
         ]
        
        
        
//        let baseSalary = orderDetail.baseIncome > 0 ? "$\(orderDetail.baseIncome)" : "暂无计算"
//        let rewardIncome = orderDetail.rewardIncome > 0 ? "$\(orderDetail.rewardIncome)" : "暂无计算"
//        let subsidyDistance = orderDetail.subsidyIncome > 0 ? "$\(orderDetail.subsidyIncome)" : "暂无计算"
//        let salaryTotal = orderDetail.totalIncome > 0 ? "$\(orderDetail.totalIncome)" : "暂无计算"
        
        let baseSalary = "$\(orderDetail.baseIncome)"
        let rewardIncome = "$\(orderDetail.rewardIncome)"
        let subsidyDistance = "$\(orderDetail.subsidyIncome)"
        let salaryTotal = "$\(orderDetail.totalIncome)"
        
        let incomeDetails = [
            baseSalary,
            rewardIncome,
            subsidyDistance,
            salaryTotal
          ]
        
        for(index, title) in incomeTitles.enumerated(){
            let m = SSCellModel()
            m.title = title
            m.detail = incomeDetails[index]
            m.cellHeight = 44
            self.incomeInfos.append(m)
            m.textColor = "#666666"
            if(index == 3){
                m.textColor = "#FC4242"
            }
        }
        
        let titles = [
             "服务日期",
             "服务地址",
             "门牌号",
             "邮编",
             "联系人",
             "联系电话",
             "备注",
         ]
         
         let details = [
                orderDetail.serviceTime,
                orderDetail.serviceAddr,
                orderDetail.houseNo,
                orderDetail.zip,
                orderDetail.contact,
                orderDetail.contactPhone,
                orderDetail.note
          ]
         
         for(index, title) in titles.enumerated(){
             let m = SSCellModel()
             m.title = title
             m.detail = details[index]
             if(m.detail.count == 0){
                 m.detail = "无"
             }
             self.contactInfos.append(m)
             
             let size = CGSize(width: ScreenWidth - 80 - 16*3, height: CGFloat.zero)
             let titleHeight = m.detail.sizeWithText(font: UIFont.systemFont(ofSize: 14), size: size).height
             print("titleHeight:---\(titleHeight)")
             m.isMultiLine = titleHeight > 18
             if titleHeight > 44 {
                 m.cellHeight = titleHeight
             }else{
                 m.cellHeight = 44
             }
             print("")
         }
        
        let orderTitles = [
             "订单号",
             "下单时间",
         ]
         
         let orderDetails = [
            orderDetail.orderNo,
            orderDetail.createTime
          ]
         
         for(index, title) in orderTitles.enumerated(){
             let m = SSCellModel()
             m.title = title
             m.detail = orderDetails[index]
             m.cellHeight = 44
             self.orderInfos.append(m)

         }
        
        
    
         
         self.tableView.reloadData()
         
    }
    
    func setupUIs() {
        title = "订单详情"

        tableView.register(UINib(nibName: "SSOrderDetailCell", bundle: Bundle.init(for: SSOrderDetailCell.self)), forCellReuseIdentifier: "SSOrderDetailCell")
        tableView.register(UINib(nibName: "SSOrderDetailMealCell", bundle: Bundle.init(for: SSOrderDetailMealCell.self)), forCellReuseIdentifier: "SSOrderDetailMealCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
    }
    
    func network() {
        let param = [
            "phoneNo": kUserPhone,
            "orderNo":orderNo
        ] as [String:AnyObject]
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.getDetail_URL, parameters: param) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["retMsg"].stringValue
                if(retCode == "0000"){
                    let json = JSON(parseJSON: result!)
                    let data = json["data"].dictionary
                    let orderDetail = SSOrder()
                    orderDetail.baseIncome = data!["baseIncome"]?.floatValue ?? 0
                    orderDetail.rewardIncome = data!["rewardIncome"]?.floatValue ?? 0
                    orderDetail.subsidyIncome = data!["subsidyIncome"]?.floatValue ?? 0
                    orderDetail.totalIncome = data!["totalIncome"]?.floatValue ?? 0
                    
                    orderDetail.orderNo = data?["orderNo"]?.stringValue ?? ""
                    orderDetail.serviceTime = data!["serviceTime"]!.stringValue
                    orderDetail.serviceAddr = data!["serviceAddr"]!.stringValue
                    orderDetail.houseNo = data!["houseNo"]!.stringValue
                    orderDetail.zip = data!["zip"]!.stringValue
                    orderDetail.contact = data!["contact"]!.stringValue
                    orderDetail.contactPhone = data!["contactPhone"]!.stringValue
                    orderDetail.note = data!["note"]!.stringValue
                    
                    orderDetail.createTime = data!["createTime"]!.stringValue
                    orderDetail.couponMoney = data!["couponMoney"]!.stringValue
                    orderDetail.total = data!["total"]!.stringValue
                    orderDetail.isMonth = data!["isMonth"]!.stringValue
                    
                    orderDetail.pendingMoney = data!["pendingMoney"]!.floatValue
                    orderDetail.originalTotal = data!["originalTotal"]!.floatValue
                    
                    //日常清洁
                    let listDay = data!["listDay"]!.arrayValue
                    let dayArr:Array<ListCombo> = self.parseItem(arr: listDay)
                    if dayArr.count > 0 {
                        self.totalArr.append(dayArr)
                        self.sectionTitles.append("日常清洁")
                    }
                    
                    
                    //退房清洁
                    let listCheckout = data!["listCheckout"]!.arrayValue
                    let checkoutArr:Array<ListCombo> = self.parseItem(arr: listCheckout)
                    if checkoutArr.count > 0 {
                        self.totalArr.append(checkoutArr)
                        self.sectionTitles.append("退房清洁")
                    }
                    
                    //深度清洁
                    let listDeep = data!["listDeep"]!.arrayValue
                    let deepArr:Array<ListCombo> = self.parseItem(arr: listDeep)
                    if deepArr.count > 0 {
                        self.totalArr.append(deepArr)
                        self.sectionTitles.append("深度清洁")
                    }
                    
                    //蒸汽地毯
                    let listCarpet = data!["listCarpet"]!.arrayValue
                    let carpetArr:Array<ListCombo> = self.parseItem(arr: listCarpet)
                    if carpetArr.count > 0 {
                        self.totalArr.append(carpetArr)
                        self.sectionTitles.append("蒸汽地毯")
                    }
                    
                    //日式清洁
                    let listDayLife = data!["listDayLife"]!.arrayValue
                    let dayLifeArr:Array<ListCombo> = self.parseItem(arr: listDayLife)
                    if dayLifeArr.count > 0 {
                        self.totalArr.append(dayLifeArr)
                        self.sectionTitles.append("日式清洁")
                    }
                    
                    //公寓清洁
                    let listAirbnb = data!["listAirbnb"]!.arrayValue
                    let listAirbnbArr:Array<ListCombo> = self.parseItem(arr: listAirbnb)
                    if listAirbnbArr.count > 0 {
                        self.totalArr.append(listAirbnbArr)
                        self.sectionTitles.append("公寓清洁")
                    }
                    
                    
                    //后两个区占位
                    self.totalArr.append([])
                    self.totalArr.append([])
                    self.totalArr.append([])
                    self.totalArr.append([])
                    self.orderDetail = orderDetail
                    self.handleData()
                    self.tableView.reloadData()
                }else{
                    dissmissToTast(msg: retMsg)
                }

            }else{
//                if let message = error?.userInfo["errorinfo"]{
//                    self.view.makeToast(message as? String)
//                }
            }
        }
    }
    
    func parseItem(arr:[JSON]) -> Array<ListCombo> {
        var arrM:Array<ListCombo> = []
        for item in arr {
            let order = ListCombo()
            order.name = item["itemName"].stringValue
            order.fee = item["itemFee"].stringValue
            order.totalFee = item["itemTotal"].floatValue
            let listSpecs = item["listSpecs"].arrayValue
            var specHeight:CGFloat = 0
            for subItem in listSpecs {//规格
                let spec = SSSpec()
                spec.name = subItem["specsName"].stringValue
                order.specs.append(spec)
                let size = CGSize(width: ScreenWidth - 50 - 16, height: CGFloat.zero)
                let titleHeight = spec.name.sizeWithText(font: UIFont.systemFont(ofSize: 14), size: size).height
                specHeight = titleHeight + specHeight + 6
            }
            if order.specs.count > 0 {
                order.cellHeight = 56 + specHeight
            }else{
                order.cellHeight = 56
            }
//                    orderDetail.listDetail.append(order)
            arrM.append(order)
        }
        return arrM
    }

}

extension SSOrderDetailController: UITableViewDelegate, UITableViewDataSource
{
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 54
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//        if section == (totalArr.count - 4) {
//            return 50
//        }
        return 0.01
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.totalArr.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (section == (totalArr.count - 1)) {
            return contactInfos.count
        }
        if (section == (totalArr.count - 2)) {
            return orderInfos.count
        }
        if (section == (totalArr.count - 3)) {
            return incomeInfos.count
        }
        if (section == (totalArr.count - 4)) {
            return salaryInfos.count
        }
        return totalArr[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var resultCell = UITableViewCell()
        if (indexPath.section == (totalArr.count - 1)) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SSOrderDetailCell") as! SSOrderDetailCell
            let model = self.contactInfos[indexPath.row]
            cell.titleLab.text = model.title
            cell.detailLab.text = model.detail
            cell.detailLab.textAlignment = .right
            cell.copyImg.isHidden = true
            if(model.isMultiLine){
                cell.detailLab.textAlignment = .left
            }else{
                cell.detailLab.textAlignment = .right
            }
            resultCell = cell
            return resultCell
        }
        if (indexPath.section == (totalArr.count - 2)) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SSOrderDetailCell") as! SSOrderDetailCell
            cell.copyImg.isHidden = indexPath.row == 1
//            cell.isImage = indexPath.row == 0
            let model = self.orderInfos[indexPath.row]
            cell.titleLab.text = model.title
            cell.detailLab.text = model.detail
            resultCell = cell
            return resultCell
        }
        
        if(indexPath.section == (totalArr.count - 3)){
            let cell = tableView.dequeueReusableCell(withIdentifier: "SSOrderDetailCell") as! SSOrderDetailCell
            let model = self.incomeInfos[indexPath.row]
            cell.titleLab.text = model.title
            cell.detailLab.text = model.detail
            cell.detailLab.textColor = UIColor(hex: model.textColor)
            resultCell = cell
            return resultCell
        }
        if(indexPath.section == (totalArr.count - 4)){
            let cell = tableView.dequeueReusableCell(withIdentifier: "SSOrderDetailCell") as! SSOrderDetailCell
            let model = self.salaryInfos[indexPath.row]
            cell.titleLab.text = model.title
            cell.detailLab.text = model.detail
            cell.detailLab.textColor = UIColor(hex: model.textColor)
            resultCell = cell
            return resultCell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "SSOrderDetailMealCell") as! SSOrderDetailMealCell
        cell.setData(order: totalArr[indexPath.section][indexPath.row], index: indexPath.row)
        resultCell = cell
        return resultCell

    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        if (indexPath.section == (totalArr.count - 1)) {
            return contactInfos[indexPath.row].cellHeight
        }
        if (indexPath.section == (totalArr.count - 2)) {
            return orderInfos[indexPath.row].cellHeight
        }
        if (indexPath.section == (totalArr.count - 3)) {
            return incomeInfos[indexPath.row].cellHeight
        }
        if (indexPath.section == (totalArr.count - 4)) {
            return salaryInfos[indexPath.row].cellHeight
        }
        let arr = totalArr[indexPath.section]
        return arr[indexPath.row].cellHeight
    }
   
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var title = ""
        if self.sectionTitles.count > 0 {
            title = self.sectionTitles[section]
        }
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 54))
        view.backgroundColor = UIColor.white
        
        if((section == totalArr.count - 1)||(section == totalArr.count - 2)||(section == totalArr.count - 3)||(section == totalArr.count - 4)){
            let sectionView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 6))
            sectionView.backgroundColor = UIColor.init(hex: "#e5e5e5")
            view.addSubview(sectionView)
        }
        
        let label = UILabel()
        label.text = title
        label.font = UIFont.systemFont(ofSize: 16,weight: .medium)
        label.textColor = UIColor.black
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.width.equalTo(150)
            make.height.equalTo(22)
            make.left.equalTo(16)
            make.top.equalTo(22)
        }
        return view
    }
    
//    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        if section != 0 {
//            return UIView()
//        }
//        let view = UIView(frame: CGRect(x: 0, y: 6, width: tableView.frame.width, height: 54))
//    //        view.backgroundColor = UIColor.red
//        let lineView = UIView()
//        lineView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 1)
//        lineView.backgroundColor = UIColor.black.withAlphaComponent(0.3)
//        view.addSubview(lineView)
//
//        let y:CGFloat = 14
//        let width:CGFloat = 120
//
//        let label = UILabel()
//        label.textAlignment = .right
//    //        label.backgroundColor = UIColor.green
//        label.text = "总计$\(orderDetail.total)"
//        label.font = UIFont.systemFont(ofSize: 14,weight: .medium)
//        label.textColor = UIColor.init(hex: "666666")
//        view.addSubview(label)
//        label.frame = CGRect(x: ScreenWidth - width - 16, y: y, width: width, height: 20)
//
//        let string = label.text
//        let attributedString = NSMutableAttributedString(string:string ?? "")
//        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.init(hex: "#000000")!, range: NSRange(location: 2, length: string!.count - 2))
//        label.attributedText = attributedString
//
//        if orderDetail.couponMoney.count == 0 {
//            orderDetail.couponMoney = "0.0"
//        }
//
//        let label2 = UILabel()
//        label2.textAlignment = .left
//    //        label2.backgroundColor = UIColor.red
//        label2.text = "总优惠$\(orderDetail.couponMoney)"
//        label2.font = UIFont.systemFont(ofSize: 14,weight: .medium)
//        label2.textColor = UIColor.init(hex: "666666")
//        view.addSubview(label2)
//        label2.frame = CGRect(x: ScreenWidth - width - 110, y: y, width: width, height: 20)
//
//        let string2 = label2.text
//        let attributedString2 = NSMutableAttributedString(string:string2 ?? "")
//        attributedString2.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.init(hex: "#FC4242")!, range: NSRange(location: 3, length: string2!.count - 3))
//        label2.attributedText = attributedString2
//
//        return view
//    }
 
}

class SSCellModel: NSObject {
    var title: String = ""
    var detail: String = ""
    var textColor: String = ""
    var cellHeight: CGFloat = 0
    var isMultiLine: Bool = false
    required override init() {}
}

//func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//    if section != (totalArr.count - 4) {
//        return UIView()
//    }
//    let view = UIView(frame: CGRect(x: 0, y: 6, width: tableView.frame.width, height: 54))
////        view.backgroundColor = UIColor.red
//    let lineView = UIView()
//    lineView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 1)
//    lineView.backgroundColor = UIColor.black.withAlphaComponent(0.3)
//    view.addSubview(lineView)
//
//    let y:CGFloat = 14
//    let width:CGFloat = 120
//
//    let label = UILabel()
//    label.textAlignment = .right
////        label.backgroundColor = UIColor.green
//    label.text = "总计$\(orderDetail.total)"
//    label.font = UIFont.systemFont(ofSize: 14,weight: .medium)
//    label.textColor = UIColor.init(hex: "666666")
//    view.addSubview(label)
//    label.frame = CGRect(x: ScreenWidth - width - 16, y: y, width: width, height: 20)
//
//    let string = label.text
//    let attributedString = NSMutableAttributedString(string:string ?? "")
//    attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.init(hex: "#000000")!, range: NSRange(location: 2, length: string!.count - 2))
//    label.attributedText = attributedString
//
//    if orderDetail.couponMoney.count == 0 {
//        orderDetail.couponMoney = "0.0"
//    }
//
//    let label2 = UILabel()
//    label2.textAlignment = .left
////        label2.backgroundColor = UIColor.red
//    label2.text = "总优惠$\(orderDetail.couponMoney)"
//    label2.font = UIFont.systemFont(ofSize: 14,weight: .medium)
//    label2.textColor = UIColor.init(hex: "666666")
//    view.addSubview(label2)
//    label2.frame = CGRect(x: ScreenWidth - width - 110, y: y, width: width, height: 20)
//
//    let string2 = label2.text
//    let attributedString2 = NSMutableAttributedString(string:string2 ?? "")
//    attributedString2.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.init(hex: "#FC4242")!, range: NSRange(location: 3, length: string2!.count - 3))
//    label2.attributedText = attributedString2
//
//    return view
//}
